package com.awise.app.sunrise.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.VideoView;

import com.awise.R;
import com.awise.base.BaseActivity;
import com.awise.http.RoverGlobal;
import com.awise.util.Constant;
import com.awise.view.ProgressBarView;

import java.util.Timer;
import java.util.TimerTask;


/**
 * Created by lgz on 2018/1/23.
 */

public class SunriseActivity extends BaseActivity implements View.OnClickListener {
    private VideoView videoView;
    private RelativeLayout rllayout;
    private ProgressBarView circle_progress_bar4;
    private LinearLayout ll_time_night, ll_time_morning, ll_progress_layout;
    private TextView tv_time_night, tv_time_morning;
    private CheckBox cb_week_1, cb_week_2, cb_week_3, cb_week_4, cb_week_5, cb_week_6, cb_week_7, cb_week_all;
    private PopupWindow mPopWindow;
    private TextView tv_sunrise_pop_cannel, tv_sunrise_pop_download;
    private RelativeLayout rl_slow_layout, rl_fast_layout;
    private View contentView;
    private TextView dialog_tv;
    private Switch on_off;
    private boolean week_7, week_1, week_2, week_3, week_4, week_5, week_6;
    private ImageView  iv_pic;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sunrise_layout);
        initView();
        readData();
        String DisplayMode= getIntent().getStringExtra("DisplayMode");
        if(!TextUtils.isEmpty(DisplayMode)){
            iv_pic.setVisibility(View.GONE);
            on_off.setVisibility(View.GONE);
        }
        showLoadingView();
        LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, new IntentFilter(Constant.SUNRISE_ACTION));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver);
    }

    private void initView() {
        videoView = (VideoView) this.findViewById(R.id.sunrise_videoView);
        rllayout = (RelativeLayout) this.findViewById(R.id.sunrise_rl_vv_layout);
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) rllayout.getLayoutParams();
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        videoView.setLayoutParams(layoutParams);
        Uri uri = Uri.parse("android.resource://com.awise/" + R.raw.sunrise);
        MediaController mediaCtlr = new MediaController(SunriseActivity.this);
        mediaCtlr.setMediaPlayer(videoView);
        mediaCtlr.setVisibility(View.INVISIBLE); //设置隐藏
        videoView.setMediaController(mediaCtlr); // 设置视频控制器
        videoView.setOnCompletionListener(new MyPlayerOnCompletionListener());// 播放完成回调
        videoView.setVideoURI(uri); // 设置视频路径
        videoView.start(); // 开始播放视频
        TextView s_back = (TextView) this.findViewById(R.id.tv_back);
        TextView textView_content = (TextView) this.findViewById(R.id.textView_content);
        textView_content.setText(R.string.sunrise_title);
        iv_pic = (ImageView) this.findViewById(R.id.iv_pic);
        iv_pic.setImageResource(R.mipmap.download_enable_icon);
        iv_pic.setVisibility(View.VISIBLE);
        iv_pic.setOnClickListener(this);
        s_back.setVisibility(View.VISIBLE);
        s_back.setOnClickListener(this);
        circle_progress_bar4 = (ProgressBarView) this.findViewById(R.id.circle_progress_bar4);
        circle_progress_bar4.setMax(1000);
        circle_progress_bar4.setDraggingEnabled(true);
        ll_time_night = (LinearLayout) this.findViewById(R.id.ll_time_night);
        ll_time_morning = (LinearLayout) this.findViewById(R.id.ll_time_morning);
        tv_time_night = (TextView) this.findViewById(R.id.tv_time_night);
        tv_time_morning = (TextView) this.findViewById(R.id.tv_time_morning);
        ll_time_night.setOnClickListener(this);
        ll_time_morning.setOnClickListener(this);
        rl_slow_layout = (RelativeLayout) this.findViewById(R.id.rl_slow_layout);
        rl_fast_layout = (RelativeLayout) this.findViewById(R.id.rl_fast_layout);
        rl_slow_layout.setOnClickListener(this);
        rl_fast_layout.setOnClickListener(this);
        on_off = (Switch) this.findViewById(R.id.on_off);
        on_off.setOnClickListener(this);


        circle_progress_bar4.setOnRefreshTimeListener(new ProgressBarView.TimeListener() {
            @Override
            public void setRefreshTimeListener(int progress, int timeType) {
                double TotalTime = progress * 0.18;
                int hour = 5;
                double Minute = 0;
                String MinuteTime = "";
                String HourTime = "";
                if (TotalTime >= 0 && TotalTime < 60) {
                    hour = 0;
                    Minute = TotalTime;
                } else if (TotalTime >= 60 && TotalTime < 120) {
                    hour = 1;
                    Minute = TotalTime - 60;
                } else if (TotalTime >= 120 && TotalTime < 180) {
                    hour = 2;
                    Minute = TotalTime - 120;
                }
                if (Minute < 10 && Minute >= 0) {
                    MinuteTime = "0" + (int) Minute;
                } else {
                    MinuteTime = (int) Minute + "";
                }
//                System.out.println("TotalTime:" + TotalTime + ";MinuteTime=" + MinuteTime);
                if (circle_progress_bar4.night == timeType) {
                    hour += 17;
                    tv_time_night.setText(hour + ":" + MinuteTime);
                     endhour= (byte) hour;
                     endmimute= (byte) Minute;
                } else if (circle_progress_bar4.morning == timeType) {
                    hour += 5;
                    if (hour < 10 && hour >= 0) {
                        HourTime = "0" + hour;
                    } else {
                        HourTime = hour + "";
                    }
                    tv_time_morning.setText(HourTime + ":" + MinuteTime);
                    starthour = (byte) hour;
                    starminute = (byte) Minute;
                }
            }
        });
    }

    private TimerTask mTimerTask;
    private long curTime;
    private Timer mTimer;

    //初始化timer
    public void initTimer() {
        mTimerTask = new TimerTask() {
            @Override
            public void run() {
                if (curTime == 0) {
                    curTime = delaytime;
                } else {
                    //计数器，每次减一秒。
                    curTime -= 1000;
                }
                Message message = new Message();
                message.what = 110;
                message.obj = curTime;
                mHandler.sendMessage(message);
            }
        };
        mTimer = new Timer();
    }

    //实现更新主线程UI
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 110:
                    long sRecLen = (long) msg.obj;
                    //如果当前时间等于0时，则运行结束。
                    if (sRecLen <= 0) {
                        mTimer.cancel();
                        curTime = 0;
                        endTime = System.currentTimeMillis();
//                        Toast.makeText(SunriseActivity.this, "结束  "+(endTime-startTime), Toast.LENGTH_SHORT).show();
                        mPopWindow.dismiss();
                    }
                    break;
            }
        }
    };

    /**
     * destory上次使用的 Timer
     */
    public void destroyTimer() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
    }


    private long startTime, endTime;
    private int delaytime = 0;
    private byte onoffvalue = (byte) 0x00;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_back:
                if (mPopWindow!=null&&mPopWindow.isShowing()) {
                    mPopWindow.dismiss();
                    setStopPreview();
                    //如果 curTime == 0，则不需要执行此操作
                    if (curTime == 0) {
                        break;
                    }
                    curTime = 0;
                    destroyTimer();
                }
                finish();
                break;
            case R.id.on_off:
//                 0x01 (开)/0x00（关）
                onoffvalue = on_off.isChecked() ? (byte) 0x01 : (byte) 0x00;
                onoff(onoffvalue);
                break;
            case R.id.rl_slow_layout:
//                startTime=System.currentTimeMillis();
                showlaoddingwindow(R.string.slow_preview);
                setpreview((byte) 0x02);
                delaytime = 60000;
                destroyTimer();
                initTimer();
                // 参数：0，延时0秒后执行;1000，每隔1秒执行1次task。
                mTimer.schedule(mTimerTask, 0, 1000);
                break;
            case R.id.rl_fast_layout:
//                startTime=System.currentTimeMillis();
                showlaoddingwindow(R.string.fast_preview);
                setpreview((byte) 0x01);
                delaytime = 28000;
                destroyTimer();
                initTimer();
                // 参数：0，延时0秒后执行;1000，每隔1秒执行1次task。
                mTimer.schedule(mTimerTask, 0, 1000);
                break;
            case R.id.ll_progress_layout:
                mPopWindow.dismiss();
                setStopPreview();
                //如果 curTime == 0，则不需要执行此操作
                if (curTime == 0) {
                    break;
                }
                curTime = 0;
                destroyTimer();
                break;
            case R.id.ll_time_night:
                String[] array = tv_time_night.getText().toString().split(":");
                int hour = Integer.valueOf(array[0]);
                int minute = Integer.valueOf(array[1]);
                int totalTime = (hour - 17) * 60 + minute;
                int progress = (1000 * totalTime) / 180;
                circle_progress_bar4.setProgress(progress);
                circle_progress_bar4.setTime(circle_progress_bar4.night);
                break;
            case R.id.ll_time_morning:
                String[] array2 = tv_time_morning.getText().toString().split(":");
                int hour2 = Integer.valueOf(array2[0]);
                int minute2 = Integer.valueOf(array2[1]);
                int totalTime2 = (hour2 - 5) * 60 + minute2;
                int progress2 = (1000 * totalTime2) / 180;
                circle_progress_bar4.setProgress(progress2);
                circle_progress_bar4.setTime(circle_progress_bar4.morning);
                break;
            case R.id.iv_pic:
                showPopupWindow(week_1, week_2, week_3, week_4, week_5, week_6,week_7);
                break;
            case R.id.tv_sunrise_pop_cannel:
                if (mPopWindow != null) {
                    mPopWindow.dismiss();
                }
                break;
            case R.id.tv_sunrise_pop_download:
                int weekValue = 0;
                if (week_1) {
                    weekValue += 1;
                }
                if (week_2) {
                    weekValue += (1 << 1);
                }
                if (week_3) {
                    weekValue += (1 << 2);
                }
                if (week_4) {
                    weekValue += (1 << 3);
                }
                if (week_5) {
                    weekValue += (1 << 4);
                }
                if (week_6) {
                    weekValue += (1 << 5);
                }
                if (week_7) {
                    weekValue += (1 << 6);
                }
                download((byte) weekValue);
                if (mPopWindow != null) {
                    mPopWindow.dismiss();
                }
                break;
            case R.id.cb_week_1:
                cb_week_1.setChecked(cb_week_1.isChecked());
                week_1 = cb_week_1.isChecked();
                setRefreshCheckbox();
                break;
            case R.id.cb_week_2:
                cb_week_2.setChecked(cb_week_2.isChecked());
                week_2 = cb_week_2.isChecked();
                setRefreshCheckbox();
                break;
            case R.id.cb_week_3:
                cb_week_3.setChecked(cb_week_3.isChecked());
                week_3 = cb_week_3.isChecked();
                setRefreshCheckbox();
                break;
            case R.id.cb_week_4:
                cb_week_4.setChecked(cb_week_4.isChecked());
                week_4 = cb_week_4.isChecked();
                setRefreshCheckbox();
                break;
            case R.id.cb_week_5:
                cb_week_5.setChecked(cb_week_5.isChecked());
                week_5 = cb_week_5.isChecked();
                setRefreshCheckbox();
                break;
            case R.id.cb_week_6:
                cb_week_6.setChecked(cb_week_6.isChecked());
                week_6 = cb_week_6.isChecked();
                setRefreshCheckbox();
                break;
            case R.id.cb_week_7:
                cb_week_7.setChecked(cb_week_7.isChecked());
                week_7 = cb_week_7.isChecked();
                setRefreshCheckbox();
                break;
            case R.id.cb_week_all:
                cb_week_all.setChecked(cb_week_all.isChecked());
                boolean flag = cb_week_all.isChecked();
                cb_week_1.setChecked(flag);
                cb_week_2.setChecked(flag);
                cb_week_3.setChecked(flag);
                cb_week_4.setChecked(flag);
                cb_week_5.setChecked(flag);
                cb_week_6.setChecked(flag);
                cb_week_7.setChecked(flag);
                week_1 = week_2 = week_3 = week_4 = week_5 = week_6 = week_7 = flag;
                break;


        }
    }


    private void setRefreshCheckbox() {
        if (cb_week_1.isChecked() && cb_week_2.isChecked() && cb_week_3.isChecked()
                && cb_week_4.isChecked() && cb_week_5.isChecked() && cb_week_6.isChecked()
                && cb_week_7.isChecked()) {
            cb_week_all.setChecked(true);
        } else {
            cb_week_all.setChecked(false);
        }
    }


    @Override
    public void onStart() {
        super.onStart();
        if (videoView != null)
            videoView.start(); // 开始播放视频
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    class MyPlayerOnCompletionListener implements MediaPlayer.OnCompletionListener {
        @Override
        public void onCompletion(MediaPlayer mp) {
            videoView.start();
            mp.setLooping(true);
        }
    }

    private void showPopupWindow(boolean week_1,boolean week_2,boolean week_3,boolean week_4,boolean week_5,boolean week_6,boolean week_7) {
        //设置contentView
        View contentView = LayoutInflater.from(this).inflate(R.layout.sunrise_downloading_popwindow_layout, null);
        mPopWindow = new PopupWindow(contentView,
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT, true);
        //设置各个控件的点击响应
        cb_week_1 = (CheckBox) contentView.findViewById(R.id.cb_week_1);
        cb_week_2 = (CheckBox) contentView.findViewById(R.id.cb_week_2);
        cb_week_3 = (CheckBox) contentView.findViewById(R.id.cb_week_3);
        cb_week_4 = (CheckBox) contentView.findViewById(R.id.cb_week_4);
        cb_week_5 = (CheckBox) contentView.findViewById(R.id.cb_week_5);
        cb_week_6 = (CheckBox) contentView.findViewById(R.id.cb_week_6);
        cb_week_7 = (CheckBox) contentView.findViewById(R.id.cb_week_7);
        cb_week_all = (CheckBox) contentView.findViewById(R.id.cb_week_all);
        tv_sunrise_pop_cannel = (TextView) contentView.findViewById(R.id.tv_sunrise_pop_cannel);
        tv_sunrise_pop_download = (TextView) contentView.findViewById(R.id.tv_sunrise_pop_download);
        tv_sunrise_pop_cannel.setOnClickListener(this);
        tv_sunrise_pop_download.setOnClickListener(this);
        cb_week_1.setOnClickListener(this);
        cb_week_2.setOnClickListener(this);
        cb_week_3.setOnClickListener(this);
        cb_week_4.setOnClickListener(this);
        cb_week_5.setOnClickListener(this);
        cb_week_6.setOnClickListener(this);
        cb_week_7.setOnClickListener(this);
        cb_week_all.setOnClickListener(this);
        cb_week_1.setChecked(week_1);
        cb_week_2.setChecked(week_2);
        cb_week_3.setChecked(week_3);
        cb_week_4.setChecked(week_4);
        cb_week_5.setChecked(week_5);
        cb_week_6.setChecked(week_6);
        cb_week_7.setChecked(week_7);
        setRefreshCheckbox();
        //显示PopupWindow
        View rootview = LayoutInflater.from(this).inflate(R.layout.sunrise_layout, null);
        mPopWindow.showAtLocation(rootview, Gravity.CENTER, 0, 0);
    }

    private void showlaoddingwindow(int name) {
        //设置contentView
        contentView = LayoutInflater.from(this).inflate(R.layout.custom_progress_dialog, null);
        mPopWindow = new PopupWindow(contentView,
                RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT, true);
        //设置各个控件的点击响应
        dialog_tv = (TextView) contentView.findViewById(R.id.dialog_tv);
        dialog_tv.setText(name);

        ll_progress_layout = (LinearLayout) contentView.findViewById(R.id.ll_progress_layout);
        ll_progress_layout.setOnClickListener(this);
        //显示PopupWindow
        View rootview = LayoutInflater.from(this).inflate(R.layout.sunrise_layout, null);
        mPopWindow.setOutsideTouchable(false);
        mPopWindow.setFocusable(false);
        mPopWindow.showAtLocation(rootview, Gravity.CENTER, 0, 0);
    }


    //开始预览
    private void setpreview(byte value) {
//        0xC0 0x0A	0x11	0x01	0x19	0x03   0x00 0x02
        byte[] bytes = {(byte) 0xc0, 0x0a, 0x11, 0x01, 0x19, 0x03, 0x00, 0x01, value, 0x00};
        writeData(bytes);
    }

    private void onoff(byte value) {
//     0xC0 0x0A   0x11	0x01	0x13	0xxx	0x00 0x01	0x01(开)/0x00（关）0x00
        byte[] bytes = {(byte) 0xc0, 0x0a, 0x11, 0x01, 0x13, 0x35, 0x00, 0x01, value, 0x00};
        writeData(bytes);
    }

    //停止预览
    private void setStopPreview() {
//        0xC0 0x0A	0x11	0x01	0x33	0x00	0x00 0x00  X
        byte[] bytes = {(byte) 0xc0, 0x0a, 0x11, 0x01, 0x33, 0x00, 0x00, 0x00, 0x00};
        writeData(bytes);
    }

    private byte starthour = 05;
    private byte starminute = 00;
    private byte endhour = 17;
    private byte endmimute = 00;

    private void download(byte value) {
//       C0 0A 11 01 34 00 00 06 01开关 7F星期 05 1E开始 10 02结束 CB  发送
        byte[] bytes = {(byte) 0xc0, 0x0a, 0x11, 0x01, 0x34, 0x00, 0x00, 0x06, onoffvalue, value, starthour, starminute, endhour, endmimute, 0x00};
        writeData(bytes);
    }

    //读取数据
    private void readData() {
//        C0 0A 11 01 1a 3a 00 00 30
        byte[] bytes = {(byte) 0xc0, 0x0a, 0x11, 0x01, 0x1a, 0x3a, 0x00, 0x00, 0x00};
        writeData(bytes);
    }

    public void writeData(byte[] bytes) {
        bytes[bytes.length - 1] = RoverGlobal.getInstance().getAddValue(bytes, bytes.length);
        RoverGlobal.getInstance().connect.write(bytes);
    }

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            closedLoadingView();
            if (intent.getAction() == Constant.SUNRISE_ACTION) {
                byte[] buffer = intent.getByteArrayExtra("socket_data");
                if (buffer != null) {
                    byte buffer4 = buffer[4];
                    byte buffer5 = buffer[5];
                    switch (buffer4) {
                        case 0x1a:
                            if (buffer5 == 0x3a) { // 读取日出日落
                                int dataLenght = buffer[7];
//                                0x00 0x03	开关		开始小时	开始分钟	结束小时	结束分钟
                                byte value1 = buffer[8];//开关
                                byte value2 = buffer[9];//星期
                                byte value3 = buffer[10];//开始小时
                                byte value4 = buffer[11];//开始分钟
                                byte value5 = buffer[12];//结束小时
                                byte value6 = buffer[13];//结束分钟
//                                0x01(开)/0x00(关)
                                on_off.setChecked(value1 == 0x01 ? true : false);
                                String startHour = (value3 < 10) ? ("0" + value3) : ("" + value3);
                                String startMinute = (value4 < 10) ? ("0" + value4) : ("" + value4);
                                String EndHour = (value5 < 10) ? ("0" + value5) : ("" + value5);
                                String EndMinute = (value6 < 10) ? ("0" + value6) : ("" + value6);

                                starthour = value3;
                                starminute = value4;
                                endhour = value5;
                                endmimute = value6;
                                onoffvalue = value1;

                                startTime = (value3 - 5) * 60 + value4;
                                endTime = (value5 - 17) * 60 + value6;
                                tv_time_morning.setText(startHour + ":" + startMinute);
                                tv_time_night.setText(EndHour + ":" + EndMinute);
                                circle_progress_bar4.setProgress(startTime * 1000 / 180);
//                                System.out.println("progress 星期0 :" + value2);
                                week_1 = (value2 % 2 == 1) ? true : false;
                                week_2 = ((value2 >> 1) % 2 == 1) ? true : false;
                                week_3 = ((value2 >> 2) % 2 == 1) ? true : false;
                                week_4 = ((value2 >> 3) % 2 == 1) ? true : false;
                                week_5 = ((value2 >> 4) % 2 == 1) ? true : false;
                                week_6 = ((value2 >> 5) % 2 == 1) ? true : false;
                                week_7 = ((value2 >> 6) % 2 == 1) ? true : false;
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
        }
    };

}
